package com.robotserver.orders.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLDecoder;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.TreeMap;


public class ApiSignUtil {
	private static Logger logger =  LoggerFactory.getLogger(ApiSignUtil.class);

	public static String getSign(TreeMap<String, Object> treeMap,String key) {
		if (treeMap==null) {
			return "";
		}
		String ascStr = toAscString(treeMap) + String.format("key=%s", key );
		//logger.info("sign param:{}",ascStr);
		return md5(ascStr);
	}
	private static String toAscString(TreeMap<String, Object> treeMap) {
		StringBuilder buf = new StringBuilder();
		try {
			Iterator<Entry<String, Object>> it = treeMap.entrySet().iterator();
			while (it.hasNext()) {
				Entry<String, Object> entry = it.next();
				//对一些特殊符号先进行转换成URL编码
				String value = entry.getValue().toString();
				value = value.replace("%","%25");
				value = value.replace("+","%2b");
				buf.append(String.format("%s=%s", entry.getKey(), URLDecoder.decode(value, "UTF-8")));
			}
		} catch (Exception e) {
			logger.error("getAscString.Exception:", e);
		}
		return buf.toString();
	}

	private static String md5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str).toLowerCase();
		} catch (Exception e) {
			logger.error("md5.Exception", e);
			return null;
		}
	}
	
	
	public static void main(String[] args) {
		TreeMap<String, Object> treeMap = new TreeMap<>();
		treeMap.put("beginTime","2019-10-07 19:30:00");
		treeMap.put("endTime","2019-10-07 20:00:00");
		treeMap.put("token","d99a365a29404a08ac08b9e52c66f878");
		treeMap.put("uid","1156559898881646594");
		System.out.println(getSign(treeMap,"06d573d28f9a0c15c764df6542dfbcd6"));;
	}
}
